/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.thinkgem.jeesite.common.utils.BarcodeUtil;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.biz.dao.*;
import com.thinkgem.jeesite.modules.biz.entity.*;
import com.thinkgem.jeesite.modules.biz.form.BizReturnBarterDetailForm;
import com.thinkgem.jeesite.modules.biz.form.BizReturnBarterForm;
import com.thinkgem.jeesite.modules.sys.utils.AutoNameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 退换货Service
 * @author xuchen
 * @version 2018-09-10
 */
@Service
@Transactional(readOnly = true)
public class SmReturnBarterService extends CrudService<SmReturnBarterDao, SmReturnBarter> {

	@Autowired
	private SmReturnBarterDao smReturnBarterDao;
	@Autowired
	private SmReturnBarterDetailDao smReturnBarterDetailDao;
	@Autowired
	private BizOrderService bizOrderService;
	@Autowired
	private BizGoodsService bizGoodsService;
	@Autowired
	private BizOrderdetailService bizOrderdetailService;
	@Autowired
	private BizGoodsDao bizGoodsDao;
	@Autowired
	private BizOrderDao bizOrderDao;

	
	public SmReturnBarter get(String id) {
		return super.get(id);
	}
	
	public List<SmReturnBarter> findList(SmReturnBarter smReturnBarter) {
		return super.findList(smReturnBarter);
	}
	
	public Page<SmReturnBarter> findPage(Page<SmReturnBarter> page, SmReturnBarter smReturnBarter) {
		return super.findPage(page, smReturnBarter);
	}
	
	@Transactional(readOnly = false)
	public void save(SmReturnBarter smReturnBarter) {
		//当前登录用户
		User loginUser = UserUtils.getUser();
		if(smReturnBarter != null){
			//新创建的状态为待提交
			if(StringUtils.isEmpty(smReturnBarter.getId())){
				smReturnBarter.setAuditStatus("40");
			}
			super.save(smReturnBarter);
			//先将现在退换货单下的退货商品全部删除
			smReturnBarterDetailDao.deleteByReturnBarterId(smReturnBarter.getId());
			//退货商品
			List<SmReturnBarterDetail> smReturnDetailList = smReturnBarter.getSmReturnDetailList();
			if(smReturnDetailList != null && smReturnDetailList.size() > 0){
				for (SmReturnBarterDetail returnDetail : smReturnDetailList) {
					if(returnDetail != null){
						if("0".equals(returnDetail.getDelFlag())){
							//新增
							returnDetail.preInsert();
							returnDetail.setReturnBarterId(smReturnBarter.getId());
							returnDetail.setType("10");
							returnDetail.setCreateBy(loginUser);
							returnDetail.setCreateDate(new Date());
							if(returnDetail.getQuantity() == null){
								returnDetail.setQuantity(0);
							}
							smReturnBarterDetailDao.insert(returnDetail);
						}else{
							//删除
							smReturnBarterDetailDao.delete(returnDetail);
						}
					}
				}
			}
			
			//换货商品
			List<SmReturnBarterDetail> smBarterDetailList = smReturnBarter.getSmBarterDetailList();
			if(smBarterDetailList != null && smBarterDetailList.size() > 0){
				for (SmReturnBarterDetail barterDetail : smBarterDetailList) {
					if(barterDetail != null){
						if("0".equals(barterDetail.getDelFlag())){
							//新增
							barterDetail.preInsert();
							barterDetail.setReturnBarterId(smReturnBarter.getId());
							barterDetail.setType("20");
							barterDetail.setCreateBy(loginUser);
							barterDetail.setCreateDate(new Date());
							smReturnBarterDetailDao.insert(barterDetail);
						}else{
							//删除
							smReturnBarterDetailDao.delete(barterDetail);
						}
					}
				}
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(SmReturnBarter smReturnBarter) {
		super.delete(smReturnBarter);
	}

	@Transactional(readOnly = false)
	public void submitAudit(SmReturnBarter smReturnBarter) {
		smReturnBarterDao.submitAudit(smReturnBarter);
	}

	/**
	 * 处理CRM发送的退换货单
	 * @param bizReturnBarterForm
	 */
	@Transactional(readOnly = false)
    public void saveFromCrm(BizReturnBarterForm bizReturnBarterForm) {
		//非空校验
		if(bizReturnBarterForm != null){
			String returnBarterId = bizReturnBarterForm.getId();
			if(StringUtils.isNotEmpty(returnBarterId)){
				SmReturnBarter smReturnBarter = new SmReturnBarter();
				//将bizReturnBarterForm中的属性设置到smReturnBarter对象中
				smReturnBarter.setId(bizReturnBarterForm.getId());
				smReturnBarter.setName(bizReturnBarterForm.getName());
				smReturnBarter.setCategory(bizReturnBarterForm.getCategory());
				smReturnBarter.setGoodsType(bizReturnBarterForm.getGoodsType());
				smReturnBarter.setCustomerId(bizReturnBarterForm.getCustomerId());
				smReturnBarter.setCustomerName(bizReturnBarterForm.getCustomerName());
				smReturnBarter.setPhone(bizReturnBarterForm.getPhone());
				smReturnBarter.setAddress(bizReturnBarterForm.getAddress());
				smReturnBarter.setAuditStatus("10");
				User createBy = new User();
				createBy.setId(bizReturnBarterForm.getCreateBy());
				createBy.setName(bizReturnBarterForm.getCreateByName());
				smReturnBarter.setCreateBy(createBy);
				smReturnBarter.setCreateDate(bizReturnBarterForm.getCreateDate());
				User updateBy = new User();
				updateBy.setId(bizReturnBarterForm.getUpdateBy());
				updateBy.setName(bizReturnBarterForm.getUpdateByName());
				smReturnBarter.setUpdateBy(updateBy);
				smReturnBarter.setUpdateDate(bizReturnBarterForm.getUpdateDate());
				smReturnBarter.setRemarks(bizReturnBarterForm.getRemarks());
				smReturnBarter.setDeliverType(bizReturnBarterForm.getDeliverType());
				//判断数据库中是否有此退换货单
				SmReturnBarter s = get(returnBarterId);
				if(s != null){
					//修改--
					smReturnBarterDao.update(smReturnBarter);
					//将明细对象内容删除
					smReturnBarterDetailDao.deleteByReturnBarterId(returnBarterId);
				}else{
					//新增
					smReturnBarter.setIsNewRecord(true);
					smReturnBarterDao.insert(smReturnBarter);
				}

				//明细
				List<BizReturnBarterDetailForm> bizReturnBarterDetailList = bizReturnBarterForm.getBizReturnBarterDetailList();
				if(bizReturnBarterDetailList != null && bizReturnBarterDetailList.size() > 0){
					for (BizReturnBarterDetailForm detailForm : bizReturnBarterDetailList) {
						if(detailForm != null){
							Integer quantity = detailForm.getQuantity();
							String goodsId = "";
							String goodsCode = detailForm.getGoodsCode();
							BizGoods byGoodsCode = bizGoodsService.getByGoodsCode(goodsCode);
							if(byGoodsCode != null && StringUtils.isNotEmpty(byGoodsCode.getGoodsId())){
								goodsId = byGoodsCode.getGoodsId();
							}
							SmReturnBarterDetail detail = new SmReturnBarterDetail();
							detail.preInsert();
							detail.setReturnBarterId(detailForm.getReturnBarterId());
							detail.setGoodsId(goodsId);
							detail.setGoodsName(detailForm.getGoodsName());
							detail.setQuantity(quantity);
							detail.setType(detailForm.getType());
							User createByd = new User();
							createByd.setId(detailForm.getCreateBy());
							createByd.setName(detailForm.getCreateByName());
							detail.setCreateBy(createByd);
							detail.setCreateDate(detailForm.getCreateDate());
							User updateByd = new User();
							updateByd.setId(detailForm.getUpdateBy());
							updateByd.setName(detailForm.getUpdateByName());
							detail.setUpdateBy(updateByd);
							detail.setUpdateDate(detailForm.getUpdateDate());
							detail.setRemarks(detailForm.getRemarks());
							detail.setUnitPrice(detailForm.getUnitPrice());
							detail.setStockAmount(detailForm.getStockAmount());
							detail.setIsDeliver(detailForm.getIsDeliver());
							detail.setGoodsCode(goodsCode);
							detail.setSpecifications(detailForm.getSpecifications());
							detail.setIsNewRecord(true);
							smReturnBarterDetailDao.insert(detail);
							//判断该商品是否可以发货如果可以发货就修改可用库存和待发货库存
							if("0".equals(detailForm.getIsDeliver())){
								//修改商品 可用库存和待发货库存
								if (StringUtils.isNotEmpty(goodsCode)){
									BizGoods bizGoods = bizGoodsService.getByGoodsCode(goodsCode);
									if(bizGoods != null && StringUtils.isNotEmpty(bizGoods.getGoodsId())){
										bizGoods.setWaitStockAmount(bizGoods.getWaitStockAmount() + quantity);
										bizGoods.setSureStockAmount(bizGoods.getSureStockAmount() - quantity);
										bizGoodsDao.update(bizGoods);
									}
								}
							}
						}
					}
				}
			}
		}
    }

	@Transactional(readOnly = false)
	public void approve(SmReturnBarter smReturnBarter) {
		if(smReturnBarter != null && StringUtils.isNotEmpty(smReturnBarter.getId())){
			smReturnBarterDao.approve(smReturnBarter);
			if("20".equals(smReturnBarter.getCategory())){
				//退换货明细
				List<SmReturnBarterDetail> barterDetailList = smReturnBarterDetailDao.getBarterDetailListByPid(smReturnBarter.getId());

 				ArrayList<SmReturnBarterDetail> canOutOrderDetails = new ArrayList<>();	//可以发货的明细List
				ArrayList<SmReturnBarterDetail> cannotOutOrderDetails = new ArrayList<>();	//不可以发货的明细List

				if(barterDetailList != null && barterDetailList.size() > 0){
					for (SmReturnBarterDetail smReturnBarterDetail : barterDetailList) {
						//判断订单是否可以出库或者是可以部分可出库
						if("0".equals(smReturnBarterDetail.getIsDeliver())){
							//可以发货的明细
							canOutOrderDetails.add(smReturnBarterDetail);
						}
						if("1".equals(smReturnBarterDetail.getIsDeliver())){
							//不可以发货的明细
							cannotOutOrderDetails.add(smReturnBarterDetail);
						}
					}
				}

				User user = UserUtils.getUser();
				Date newDate = new Date();

				//创建可出库订单
				BizOrder bizOrder = new BizOrder();
 				if(canOutOrderDetails != null && canOutOrderDetails.size() > 0){
					//生成出库单
					bizOrder.setId(smReturnBarter.getId());
					//设置订单属性
					bizOrder.setCustomerId(smReturnBarter.getCustomerId());
					bizOrder.setDeliverType(smReturnBarter.getDeliverType());
					bizOrder.setOrderApprovalStatus("20");	//默认审核通过出库单
					bizOrder.setCustomerName(smReturnBarter.getCustomerName());
					bizOrder.setPhone(smReturnBarter.getPhone());
					bizOrder.setAddress(smReturnBarter.getAddress());
					bizOrder.setCustomerId(smReturnBarter.getCustomerId());
					bizOrder.setOrderTime(new Date());
					bizOrder.setOrderType("1");
					String name = AutoNameUtils.createAutoNameByTableName("biz_order");
					bizOrder.setName(name);
					bizOrder.setIsCanOut("1");	//可出库
					//生成条形码的地址
					String txmPath = bizOrderService.exportDir()+name+"CKD.jpg";
					//修改出库单的条码路径
					if(txmPath.indexOf("userfiles") != -1){
						String[] paths = txmPath.split("userfiles");
						bizOrder.setTmUrl("/userfiles"+paths[1]);
					}

					BarcodeUtil.createBarcode(name, txmPath);
					bizOrder.setOrderStatus("0");
					bizOrder.setCreateBy(user);
					bizOrder.setCreateByName(user.getName());
					bizOrder.setCreateDate(newDate);
					bizOrder.setDelFlag("0");
					bizOrder.setUpdateBy(user);
					bizOrder.setUpdateDate(newDate);
					//添加出库单
					bizOrderDao.insert(bizOrder);
					for (SmReturnBarterDetail smReturnBarterDetail : canOutOrderDetails) {
						BizOrderdetail bizOrderdetail = new BizOrderdetail();
						//设置出库单明细属性
						bizOrderdetail.setOutboundOrderPid(bizOrder.getId());
						bizOrderdetail.setUnitPrice(smReturnBarterDetail.getUnitPrice());
						bizOrderdetail.setQuantity(smReturnBarterDetail.getQuantity());
						bizOrderdetail.setAmountOfMoney(smReturnBarterDetail.getUnitPrice() * smReturnBarterDetail.getQuantity());	//金额
						bizOrderdetail.setProjectdetailId(smReturnBarterDetail.getGoodsId());
						bizOrderdetail.setProjectdetailName(smReturnBarterDetail.getGoodsName());
						bizOrderdetail.setSpecification(smReturnBarterDetail.getSpecifications());
						//BizGoods bizGoods = bizGoodsService.getByGoodsCode(smReturnBarterDetail.getGoodsCode());
						bizOrderdetail.setCode(smReturnBarterDetail.getGoodsCode());
						//是否可以发货
						bizOrderdetail.setIsDeliver(smReturnBarterDetail.getIsDeliver());
						bizOrderdetail.setSurplusQuantity(smReturnBarterDetail.getQuantity());	//剩余出库数

						bizOrderdetailService.save(bizOrderdetail);
					}
				}
				//创建不可出库订单
				BizOrder bizOrderF = new BizOrder();
				if(cannotOutOrderDetails != null && cannotOutOrderDetails.size() > 0){
					//生成出库单
					bizOrderF.setId(smReturnBarter.getId()+"F");
					//设置订单属性
					bizOrderF.setCustomerId(smReturnBarter.getCustomerId());
					bizOrderF.setDeliverType(smReturnBarter.getDeliverType());
					bizOrderF.setOrderApprovalStatus("20");	//默认审核通过出库单
					bizOrderF.setCustomerName(smReturnBarter.getCustomerName());
					bizOrderF.setPhone(smReturnBarter.getPhone());
					bizOrderF.setAddress(smReturnBarter.getAddress());
					bizOrderF.setCustomerId(smReturnBarter.getCustomerId());
					bizOrderF.setOrderTime(new Date());
					bizOrderF.setOrderType("1");
					String name;
					if(StringUtils.isNotEmpty(bizOrder.getName())){
						name = bizOrder.getName()+"F";
					}else{
						name = AutoNameUtils.createAutoNameByTableName("biz_order")+"F";
					}
					bizOrderF.setName(name);
					bizOrderF.setIsCanOut("0");	//不可出库
					//生成条形码的地址
					String txmPath = bizOrderService.exportDir()+name+"CKD.jpg";
					//修改出库单的条码路径
					if(txmPath.indexOf("userfiles") != -1){
						String[] paths = txmPath.split("userfiles");
						bizOrderF.setTmUrl("/userfiles"+paths[1]);
					}

					BarcodeUtil.createBarcode(name, txmPath);
					bizOrderF.setOrderStatus("0");
					bizOrderF.setCreateBy(user);
					bizOrderF.setCreateByName(user.getName());
					bizOrderF.setCreateDate(newDate);
					bizOrderF.setDelFlag("0");
					bizOrderF.setUpdateBy(user);
					bizOrderF.setUpdateDate(newDate);
					//添加出库单
					bizOrderDao.insert(bizOrderF);
					for (SmReturnBarterDetail smReturnBarterDetail : cannotOutOrderDetails) {
						BizOrderdetail bizOrderdetail = new BizOrderdetail();
						//设置出库单明细属性
						bizOrderdetail.setOutboundOrderPid(bizOrderF.getId());
						bizOrderdetail.setUnitPrice(smReturnBarterDetail.getUnitPrice());
						bizOrderdetail.setQuantity(smReturnBarterDetail.getQuantity());
						bizOrderdetail.setAmountOfMoney(smReturnBarterDetail.getUnitPrice() * smReturnBarterDetail.getQuantity());	//金额
						bizOrderdetail.setProjectdetailId(smReturnBarterDetail.getGoodsId());
						bizOrderdetail.setProjectdetailName(smReturnBarterDetail.getGoodsName());
						bizOrderdetail.setSpecification(smReturnBarterDetail.getSpecifications());
						bizOrderdetail.setCode(smReturnBarterDetail.getGoodsCode());
						//是否可以发货
						bizOrderdetail.setIsDeliver(smReturnBarterDetail.getIsDeliver());
						bizOrderdetail.setSurplusQuantity(smReturnBarterDetail.getQuantity());	//剩余出库数

						bizOrderdetailService.save(bizOrderdetail);
					}
				}
			}
		}
	}

	@Transactional(readOnly = false)
	public void dismiss(SmReturnBarter smReturnBarter) {
		//修改对应商品的可用库存和待发货库存
		if(smReturnBarter != null && StringUtils.isNotEmpty(smReturnBarter.getId())){
			List<SmReturnBarterDetail> returnDetailList = smReturnBarter.getSmReturnDetailList();
			if(returnDetailList != null && returnDetailList.size() > 0){
				for (SmReturnBarterDetail smReturnBarterDetail : returnDetailList) {
					if(smReturnBarterDetail != null){
						if("0".equals(smReturnBarterDetail.getIsDeliver())){
							//数量
							Integer quantity = smReturnBarterDetail.getQuantity();
							//商品ID
							String goodsId = smReturnBarterDetail.getGoodsId();
							if (StringUtils.isNotEmpty(goodsId)){
								BizGoods bizGoods = bizGoodsService.get(goodsId);
								if(bizGoods != null && StringUtils.isNotEmpty(bizGoods.getGoodsId())){
									bizGoods.setWaitStockAmount(bizGoods.getWaitStockAmount() - quantity);
									bizGoods.setSureStockAmount(bizGoods.getSureStockAmount() + quantity);
									bizGoodsDao.update(bizGoods);
								}
							}
						}
					}
				}
			}
		}
		smReturnBarterDao.realDelete(smReturnBarter);
	}
}